﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace SimpleTiles.Classes
{
    public class NoteManager
    {
        private String notesFile = "Notes.xml";
        private NotesListHolder notesListHolder;

        public NoteManager()
        {
            this.notesListHolder = new NotesListHolder();
        }

        public ObservableCollection<Note> Notes { get { return notesListHolder.notesList; } }

        public void addNote(Note note)
        {
            Notes.Add(note);
        }

        public Note getByTitolo(String titolo)
        {
            foreach(Note nota in Notes){
                if (nota.Titolo.Equals(titolo))
                    return nota;
            }
            return null;
            
        }

        public void removeNote(Note note)
        {
            Notes.Remove(note);
        }

        public void clearNotes()
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            storage.DeleteFile(notesFile);
            this.Notes.Clear();
        }

        public void saveNotes()
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream stream = storage.CreateFile(notesFile);

            XmlSerializer xml = new XmlSerializer(typeof(NotesListHolder));
            xml.Serialize(stream, notesListHolder);

            stream.Close();
            stream.Dispose();
        }

        public void loadNotes()
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();

            if (storage.FileExists(notesFile))
            {
                IsolatedStorageFileStream stream = storage.OpenFile(notesFile, FileMode.Open);
                XmlSerializer xml = new XmlSerializer(typeof(NotesListHolder));

                notesListHolder = (NotesListHolder)xml.Deserialize(stream);

                stream.Close();
                stream.Dispose();
            }
            else
            {
                notesListHolder = new NotesListHolder();
            }
        }
    }
}
